<template>
  <el-container class="el-container">
    <el-header class="el-header">
      <div style="text-align: center;">{{ selectedUser.name }}</div>
    </el-header>
    <el-main class="el-main">
      <el-scrollbar class="el-scrollbar" style="height: 400px">
        <div v-for="message in chatMessages" :key="message.id"
          :class="{ 'user-message': message.mark == '用户', 'manager-message': message.mark != '用户' }">
          <el-avatar v-if="message.mark == '用户'" class="user-avatar" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
          <div class="message">
            {{ message.message }}
          </div>
          <el-avatar v-if="message.mark != '用户'" class="manager-avatar" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
        </div>
      </el-scrollbar>
    </el-main>

    <el-footer class="el-footer">
      <el-input class="el-input" type="textarea" v-model="newMessage" placeholder="请输入内容" @keyup.enter="sendMessage" />
    </el-footer>

  </el-container>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, defineProps } from 'vue';
import messageStore from '@/stores/csr/MessageStore';
import { WebSocketClient } from "../../utils/websocket";
import userInf from '../../stores/user'

const props = defineProps<{ userId: string }>();
const selectedUser = ref({} as { id: string; name: string });
selectedUser.value = { id: props.userId, name: `User ${props.userId}` };

const chatMessages = ref([]);
const newMessage = ref('');

const mesStore = messageStore()

const socket=mesStore.webSocket

const userIf=userInf()

onMounted(() => {

  const record = mesStore.getMessageRecord(props.userId)

  for (let i = 0; i < record.length; i++) {
    chatMessages.value.push(record[i])
  }

  socket.on('message', (data: any) => {
    const { mark, senderId, userName, message } = data;
    if (mark == "用户") {
      if (senderId === props.userId) {
        chatMessages.value.push({ mark: '用户', senderId: senderId, userName: userName, message: message })
      }
      mesStore.toRecordMessage(senderId, { mark, senderId, userName, message })
    }

      const userExists=mesStore.userList.find(user => user.id === senderId)
      console.log(senderId+"_"+userExists)
      if (!userExists) {
        mesStore.addUser({id: senderId,name: userName})
        mesStore.addMessageRecord(senderId)
        mesStore.toRecordMessage(senderId, { mark, senderId, userName, message })
      }

    if(mark=="系统"&&message!=null){
      chatMessages.value.push({ mark: '用户',message: message })
    }

  });

  socket.connect(userIf.user.id);
});

function sendMessage() {
  if (newMessage.value.trim()) {
    socket.send({
      type: 'message',
      mark: '客服',
      senderId: userIf.user.id,
      receiveId: props.userId,
      message: newMessage.value
    });

    chatMessages.value.push({ mark: '客服', receiveId: props.userId, message: newMessage.value })

    mesStore.toRecordMessage(props.userId, { mark: '客服', receiveId: props.userId, message: newMessage.value })

    newMessage.value = ''
  }
}
</script>

<style lang="scss" scoped>
.el-container {
  width: 1000px;

  .el-header {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .el-main {
    border-top: gray solid 2px;
    border-bottom: gray solid 2px;

    .el-scrollbar {
      display: flex;
      flex-direction: column;

      .message {
        max-width: 50%;
        word-break: break-all;
        word-wrap: break-word;
        padding: 8px;
        background-color: #66d596;
        border-radius: 10px 10px;
        margin: 5px 0px;
      }

      .user-message {
        display: flex;
        justify-content: left;
      }

      .manager-message {
        display: flex;
        justify-content: right;
      }

      .user-avatar {
        margin-right: 10px;
      }

      .manager-avatar {
        margin-left: 10px;
      }
    }
  }

  .el-footer {
    height: 150px;

    .el-input {
      margin-top: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
